/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Zen
 */
public class SocketListener extends Thread{
    
    ServerSocket server;
    List<SocketReceiver> receiver;    
    ServerManager manager;
    boolean run;
    public SocketListener(int port, ServerManager manager)
    {
        try
        {
            server=new ServerSocket(port,4,InetAddress.getLocalHost());
            receiver=new ArrayList<SocketReceiver>();
            this.manager = manager;
            run=true;
        }catch(IOException ex)
        {
        }
    }
    
    @Override
    public void run() {
        
        while(run==true)
        {
            try 
            {	
                Socket client = server.accept();
                if(client!=null)
                {
                    receiver.add(new SocketReceiver(client,this));
                    receiver.get(receiver.size()-1).start();
                    manager.RefreshConnectedNode();
                }
            }catch (IOException e) 
            {
            }
        }
        
    }
    
    public void Remove(SocketReceiver object)
    {
        object.Dispose();
        receiver.remove(object);
        manager.RefreshConnectedNode();
    }
    
    public Object Excute(String s)
    {
        return manager.getDatabasesManager().ExecuteQuery(s);
    }
    
    public void Dispose()
    {
        if(receiver.size()>0)
        {
            for(int i=0;i<receiver.size();i++)
            {
                receiver.get(i).Dispose();
            }
        }
        run=false;
    }
    public List<String> getConnectedUser()
    {
        List<String> users= new ArrayList<String>();
        for(int i=0;i<receiver.size();i++)
        {
            users.add(receiver.get(i).getClientName());
        }
        return users;
    }
    public void AlertDisconnect()
    {
        manager.RefreshConnectedNode();
    }
}
